﻿using System;
using OMR.Crawler.Core.Crawlers;

namespace OMR.Crawler.Core
{
    class Program
    {
        private static string __ENTRYPOINT = "d:\\";
        private static object _lockObj = new object();
        private static DateTime started;
        private static int fileCount = 0;

        static void Main(string[] args)
        {
            var settings = new MyCollection();
            settings.SetItem(new MyCollectionItem() { Name = "EntryPoint", Value = __ENTRYPOINT });
            settings.SetItem(new MyCollectionItem() { Name = "MaxThreadCount", Value = 30 });

            var cr = CrawlerFactory.Create(settings);

            cr.OnCrawlStarted += cr_OnCrawlStarted;
            cr.OnItemCrawled += cr_OnItemCrawled;
            cr.OnCawlError += cr_OnCawlError;
            cr.OnCrawlFinished += cr_OnCrawlFinished;

            cr.Begin();

        }

        static void cr_OnCrawlFinished(object sender, CrawlFinishedEventArgs e)
        {
            lock (_lockObj)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine((DateTime.Now - started).ToString());
                Console.WriteLine(fileCount);
                Console.ResetColor();
            }
        }

        static void cr_OnCrawlStarted(object sender, CrawlStartedEventArgs e)
        {
            lock (_lockObj)
            {
                started = DateTime.Now;
            }
        }

        static void cr_OnCawlError(object sender, CrawlErrorEventArgs e)
        {
            lock (_lockObj)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Exception.Message);
                Console.ResetColor();
            }
        }

        static void cr_OnItemCrawled(object sender, CrawledItemEventArgs e)
        {
            System.Threading.Interlocked.Increment(ref fileCount);

            lock (_lockObj)
            {
                System.Console.WriteLine(e.Current.DeepCount + ":[" + e.Current.Content.Length + "] " + e.Current.EntryPoint);
            }
        }

    }
}